package com.fengwk.support.proxy.http;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.fengwk.support.proxy.http.annotation.HttpClient;
import com.fengwk.support.util.ArrayUtils;
import com.fengwk.support.util.ReflectUtils;
import com.fengwk.support.util.StringUtils;

public class HttpProxyUtils {

	private HttpProxyUtils() {}
	
	public static HttpClient getHttpClientAnnotation(Object proxy) {
		Class<?> clazz = getProxyInterfaces(proxy);
		if (clazz != null) {
			return clazz.getAnnotation(HttpClient.class);
		}
		return null;
	}
	
	public static RequestMapping getRequestMappingByMethod(Method method) {
		return method.getAnnotation(RequestMapping.class);
	}
	
	public static PostMapping getPostMappingByMethod(Method method) {
		return method.getAnnotation(PostMapping.class);
	}
	
	public static GetMapping getGetMappingByMethod(Method method) {
		return method.getAnnotation(GetMapping.class);
	}
	
	public static Map<Integer, RequestParam> getIndexRequestParamMapByMethod(Method method) {
		return getIndexAnnotationMap(method, RequestParam.class);
	}
	
	public static Map<Integer, PathVariable> getIndexPathVariableMapByMethod(Method method) {
		return getIndexAnnotationMap(method, PathVariable.class);
	}
	
	private static Class<?> getProxyInterfaces(Object proxy) {
		Class<?>[] clazzs = proxy.getClass().getInterfaces();
		if (ArrayUtils.isNotBlank(clazzs)) {
			for (Class<?> clazz: clazzs) {
				if (ReflectUtils.hasAnnotation(clazz, HttpClient.class)) {
					return clazz;
				}
			}
		}
		return null;
	}
	
	private static <A extends Annotation> Map<Integer, A> getIndexAnnotationMap(Method method, Class<A> annotationClass) {
		Map<Integer, A> map = new LinkedHashMap<Integer, A>();
		Parameter[] parameters = method.getParameters();
		if (ArrayUtils.isNotBlank(parameters)) {
			for (int i = 0; i < parameters.length; i ++) {
				Parameter parameter = parameters[i];
				A a = parameter.getAnnotation(annotationClass);
				if (a != null) {
					map.put(i, a);
				}
			}
		}
		return map;
	}
	
	public static String getValue(String hight, String low) {
		if (StringUtils.isNotBlank(hight)) {
			return hight;
		}
		return low;
	}
	
	public static String getValue(String[] hight, String[] low) {
		if (ArrayUtils.isNotBlank(hight)) {
			return hight[0];
		} else if (ArrayUtils.isNotBlank(low)) {
			return low[0];
		}
		return null;
	}
	
}
